import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertest/models/route_model.dart';
import 'package:fluttertest/models/type_map.dart';
import 'package:fluttertest/navigation_result.dart';
import 'package:fluttertest/screens/delivery/skip_store_dialog.dart';
import 'package:fluttertest/screens/delivery/web_view_screen.dart';
import 'package:fluttertest/screens/home_screen.dart';
import 'package:fluttertest/utils/logger.dart';
import '../../models/delivery_item.dart';
import '../../utils/event_bus.dart';
import '../../utils/http_client.dart';
import 'add_item_dialog.dart';

class DeliveryFormScreen extends StatefulWidget {
  Sequence sequence;
  bool over = false;

  DeliveryFormScreen({super.key, required this.sequence, required this.over});

  @override
  State<DeliveryFormScreen> createState() => _DeliveryFormScreenState();
}

class _DeliveryFormScreenState extends State<DeliveryFormScreen> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController? _boxesController;

  TextEditingController? _piecesController;

  TextEditingController? _labelsController;

  TextEditingController? _returnBoxesController;

  // final List<DeliveryItem> _additionalItems = [];
  List<TypeMap>? _allType;

  List<TypeMap>? _allUnit;

  bool _isLoading = false;
  String _skip_reason = '';
  bool _isCompleted = false;

  @override
  void initState() {
    super.initState();
    _boxesController =
        TextEditingController(text: widget.sequence.realTrunBox.toString());
    _piecesController = TextEditingController(
        text: widget.sequence.realCompleteCount.toString());
    _labelsController =
        TextEditingController(text: widget.sequence.realTagCount.toString());
    _returnBoxesController = TextEditingController(
        text: widget.sequence.realEmptyTrunBox.toString());
    __checkInputStatus();
    loadAllType();
    loadAllUnit();
  }

  void __checkInputStatus() {
    if (widget.sequence.status <= 2 && widget.sequence.fadadaStatus < 1) {
      _isCompleted = true;
    }
  }

  // 加载货物详情的逻辑
  Future<void> _loadGoodsDetail() async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/getGodsDetail',
        data: {'id': widget.sequence.id},
      );
      if (response.data['code'] == 0) {
        if (mounted) {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('货物详情'),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (response.data['data'] != null) ...[
                      for (var item in response.data['data'])
                        Card(
                          margin: const EdgeInsets.only(bottom: 8),
                          child: ListTile(
                            title: Text(item['gdsName'] ?? ''),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('数量: ${item['shippingCount'] ?? 0}'),
                                Text('货号: ${item['gdsCode'] ?? 0}'),
                              ],
                            ),
                            isThreeLine: item['remark'] != null,
                          ),
                        ),
                    ] else
                      const Text('暂无货物信息'),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('关闭'),
                ),
              ],
            ),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '获取货物详情失败')),
          );
        }
      }
    } catch (e) {
      Logger.e(e.toString());
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

//  增加项目的逻辑
  void _addItem() {
    showDialog(
      context: context,
      builder: (context) => AddItemDialog(
        sequence: widget.sequence,
        allType: _allType!,
        allUnit: _allUnit!,
        onAdd: (item) {
          setState(() {
            widget.sequence.otherDetails?.add(item);
          });
        },
      ),
    );
  }

  // 删除项目的逻辑
  void _removeItem(int index) {
    setState(() {
      widget.sequence.otherDetails?.removeAt(index);
    });
  }

//  这里是跳过的逻辑
  Future<void> _skipStore() {
    if (widget.sequence.fadadaStatus < 1) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
            content: Text.rich(TextSpan(text: '若要跳过本店:\n请先请核对', children: [
          TextSpan(text: '周转箱回收数量\n先点击'),
          TextSpan(text: '[送货完成]', style: TextStyle(color: Colors.green)),
          TextSpan(text: '按钮后再返回点击'),
          TextSpan(text: '[跳过此店]', style: TextStyle(color: Colors.red)),
        ]))),
      );
      return Future.value();
    }
    return showDialog(
      context: context,
      builder: (context) => SkipStoreDialog(
        onConfirm: (reason, images) async {
          // 调用跳过API
          try {
            _skip_reason = reason;
            setState(() {
              widget.sequence.skipShopPic = images.length > 0 ? images[0] : '';
              widget.sequence.remark = reason;
            });
            await _submitForm();
          } catch (e) {
            // 错误处理
            print(e);
          }
        },
      ),
    );
  }

  loadAllType() async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/getAllType',
        data: {'scene': 3},
      );
      if (response.data['code'] == 0) {
        List.of(response.data['data']);
        List<dynamic> l = response.data['data'];
        setState(() {
          _allType = l.map((e) => TypeMap.fromJson(e)).toList();
        });
      }
    } catch (e) {
      // loadAllType();
      print(e);
      return null;
    }
  }

  loadAllUnit() async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/getAllType',
        data: {'scene': 1},
      );
      if (response.data['code'] == 0) {
        List.of(response.data['data']);
        List<dynamic> l = response.data['data'];
        setState(() {
          _allUnit = l.map((e) => TypeMap.fromJson(e)).toList();
        });
        // _allUnit =  response.data['data'];
      }
    } catch (e) {
      print(e);
      // loadAllType();
      return null;
    }
  }

  String? selectUtil(int itemCode) {
    var s = _allUnit?.firstWhere((e) => e.typeId == itemCode,
        orElse: () => TypeMap(
            typeId: 0,
            typeName: '暂无',
            typeStatus: 0,
            scene: 0,
            createTime: '暂无'));
    return s?.typeName;
  }

  String? selectType(int itemCode) {
    var s = _allType?.firstWhere((e) => e.typeId == itemCode,
        orElse: () => TypeMap(
            typeId: 0,
            typeName: '暂无',
            typeStatus: 0,
            scene: 0,
            createTime: '暂无'));
    return s?.typeName;
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;
    _formKey.currentState?.save();
    setState(() {
      _isLoading = true;
    });
    final response;
    try {
      if (widget.over && (_skip_reason == null || _skip_reason.isEmpty)) {
        response = await HttpClient.dio.post(
          '/follower/closeAll',
          data: {
            'id': widget.sequence.id,
            'parm': [],
            'trunBox': widget.sequence.realTrunBox ?? 0,
            'difference': [],
            'otherDifference': widget.sequence.otherDetails
                .map((item) => item.toJson())
                .toList(),
            'trunBoxCount': widget.sequence.realTrunBox ?? 0,
            'currentTrunBoxCount': 0,
            'tagCount': 0,
            'remark': _skip_reason,
            'returnBoxCount': 0,
            'boxCount': 0,
            'selectLastReturnOrders': [],
            'sequence': widget.sequence,
            'over': widget.over,
            'skipPic': widget.sequence.skipShopPic.isEmpty
                ? []
                : [widget.sequence.skipShopPic],
          },
        );
      } else {
        response = await HttpClient.dio.post(
          '/follower/finishSend',
          data: {
            'id': widget.sequence.id,
            'parm': [],
            'trunBox': widget.sequence.realTrunBox ?? 0,
            'difference': [],
            'otherDifference': widget.sequence.otherDetails
                .map((item) => item.toJson())
                .toList(),
            'trunBoxCount': widget.sequence.realTrunBox ?? 0,
            'currentTrunBoxCount': 0,
            'tagCount': 0,
            'remark': _skip_reason,
            'returnBoxCount': 0,
            'boxCount': 0,
            'selectLastReturnOrders': [],
            'sequence': widget.sequence,
            'over': widget.over,
            'skipPic': widget.sequence.skipShopPic.isEmpty
                ? []
                : [widget.sequence.skipShopPic],
          },
        );
      }
      if (response.data['code'] == 0) {
        setState(() {
          _isCompleted = false;
          widget.sequence.fadadaStatus = 1;
        });
        if (_skip_reason == null || _skip_reason.isEmpty) {
          if (mounted) {
            // 打开Web页面
            final result = await Navigator.push<NavigationResult>(
              context,
              MaterialPageRoute(
                builder: (context) => WebViewScreen(
                  url: response.data['data']['fadadaSignUrl'],
                  onComplete: () {
                    Navigator.pop(
                        context,
                        NavigationResult.popToHome(
                          message: '送货完成',
                        ));
                  },
                ),
              ),
            );
            // if (result == 'completed') {
            //   Navigator.pop(context, 'completed');
            // }
            // 处理返回结果
            if (result != null) {
              if (result.message != null) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text(result.message!)),
                );
              }

              if (result.popToRoot) {
                if (mounted) {
                  Navigator.of(context).popUntil((route) => route.isFirst);
                }
              } else if (result.needRefresh) {
                // 刷新当前页面数据
                await _loadGoodsDetail();
              }
            }
          }
        } else {
          if (mounted) {
            Navigator.pop(
                context,
                NavigationResult.skiped(
                  message: '跳过${widget.sequence.storeName}',
                ));
          }
        }
        eventBus.notifyTaskStatusChanged();
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '操作失败')),
          );
        }
      }
    } catch (e) {
      print(e);
      // 错误处理
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.sequence.storeName} - 送货确认'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _loadGoodsDetail,
          ),
        ],
      ),
      body: WillPopScope(
        onWillPop: () async {
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => const HomeScreen()),
              (route) => false);
          return false;
        },
        child: Form(
          key: _formKey,
          child: ListView(
            padding: const EdgeInsets.all(16),
            children: [
              // 基本信息输入
              TextFormField(
                controller: _boxesController,
                enabled: _isCompleted,
                decoration: const InputDecoration(
                  labelText: '实收周转箱数',
                  suffixText: '箱',
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入周转箱数';
                  }
                  return null;
                },
                onSaved: (value) {
                  setState(() {
                    widget.sequence.realTrunBox = int.parse(value!);
                  });
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                enabled: _isCompleted,
                controller: _piecesController,
                decoration: const InputDecoration(
                  labelText: '实收整件数',
                  suffixText: '件',
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入整件数';
                  }
                  return null;
                },
                onSaved: (value) {
                  setState(() {
                    widget.sequence.realCompleteCount = int.parse(value!);
                  });
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                enabled: _isCompleted,
                controller: _labelsController,
                decoration: const InputDecoration(
                  labelText: '实收价签数',
                  suffixText: '张',
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入价签数';
                  }
                  return null;
                },
                onSaved: (value) {
                  setState(() {
                    widget.sequence.realTagCount = int.parse(value!);
                  });
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                enabled: _isCompleted,
                controller: _returnBoxesController,
                decoration: const InputDecoration(
                  labelText: '回收空周转箱数',
                  suffixText: '箱',
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入回收箱数';
                  }
                  return null;
                },
                onSaved: (value) {
                  setState(() {
                    widget.sequence.realEmptyTrunBox = int.parse(value!);
                  });
                },
              ),
              const SizedBox(height: 24),

              // 其他签收项
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '其他签收项',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  MouseRegion(
                    // 添加 MouseRegion 来处理鼠标悬停
                    child: Tooltip(
                      message: _isCompleted ? '' : '当前状态不允许添加签收项',
                      preferBelow: true,
                      // 提示显示在下方
                      verticalOffset: 20,
                      // 设置垂直偏移
                      decoration: BoxDecoration(
                        // 自定义提示框样式
                        color: Colors.black.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      textStyle: const TextStyle(
                        // 自定义提示文本样式
                        color: Colors.white,
                        fontSize: 14,
                      ),
                      showDuration: const Duration(seconds: 2),
                      // 显示时长
                      triggerMode: TooltipTriggerMode.manual,
                      // 手动触发模式
                      child: TextButton.icon(
                        onPressed: _isCompleted ? _addItem : null,
                        icon: const Icon(Icons.add),
                        label: const Text('添加'),
                        style: TextButton.styleFrom(
                          disabledIconColor: Colors.grey,
                          disabledForegroundColor: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              ...widget.sequence.otherDetails.asMap().entries.map((entry) {
                final index = entry.key;
                final item = entry.value;
                return Card(
                  margin: const EdgeInsets.only(bottom: 8),
                  child: ListTile(
                    title: Text(
                        '${selectType(item.itemcode) ?? '未知'} ${item.actualamount} ${item.reason}'),
                    subtitle: Text(item.comment),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete_outline),
                      onPressed: () => _isCompleted ? _removeItem(index) : null,
                    ),
                  ),
                );
              }),
            ],
          ),
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: _isLoading ? null : _skipStore,
                  child: const Text('跳过此店'),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: ElevatedButton(
                  onPressed: _isLoading ? null : _submitForm,
                  child: _isLoading
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                          ),
                        )
                      : const Text('送货完成'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
